
#import "JYTabBarButton.h"

#define JYTabBarButtonImageRatio 0.8

@implementation JYTabBarButton

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // 图片居中
        self.imageView.contentMode = UIViewContentModeScaleToFill;
        
    }
    return self;
}

// 内部图片的frame
/*- (CGRect)imageRectForContentRect:(CGRect)contentRect
{
    CGFloat imageW = self.width;
    CGFloat imageH = self.height * JYTabBarButtonImageRatio;
    CGFloat imageY = (contentRect.size.height - imageH) / 2;
    
    return CGRectMake(0, imageY, imageW, imageH);
} */

- (void)setItem:(UITabBarItem *)item
{
    _item = item;
    // 图标
    [self setImage:item.image forState:UIControlStateNormal];
    // 选中的图标
    [self setImage:item.selectedImage forState:UIControlStateDisabled];
    // self监听item的4个属性值的改变
    [item addObserver:self forKeyPath:@"image" options:0 context:nil];
    [item addObserver:self forKeyPath:@"selectedImage" options:0 context:nil];
}

- (void)dealloc
{
    [self.item removeObserver:self forKeyPath:@"image"];
    [self.item removeObserver:self forKeyPath:@"selectedImage"];
}
/**
 *  当利用KVO监听到某个对象的属性改变了, 就会调用这个方法
 */
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    // 设置图片
    [self setImage:self.item.image forState:UIControlStateNormal];
    [self setImage:self.item.selectedImage forState:UIControlStateDisabled];
}

- (void)setHighlighted:(BOOL)highlighted{}

@end
